package com.diy.sigmund.diyorder.common.middleware.mq;

import com.diy.sigmund.diycommon.entity.base.exception.DiyRuntimeException;
import com.diy.sigmund.diyorder.common.spring.config.CustomRocketMQConfig;
import javax.annotation.PostConstruct;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.LocalTransactionExecuter;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author snowalker
 * @version 1.0
 * @date 2019/6/15 10:43
 * @className SecKillChargeOrderProducer
 * @desc 秒杀订单生产者初始化
 */
@Component
public class SecKillChargeOrderProducer {

    private static final Logger LOG = LoggerFactory.getLogger(SecKillChargeOrderProducer.class);

    @Autowired
    CustomRocketMQConfig customRocketMQConfig;

    private DefaultMQProducer defaultMQProducer;

    @PostConstruct
    public void init() {
        // 事务消息
        // TransactionMQProducer transactionMQProducer = new TransactionMQProducer();
        // transactionMQProducer.setTransactionListener(new TransactionListener() {
        //     @Override
        //     public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        //         return null;
        //     }
        //
        //     @Override
        //     public LocalTransactionState checkLocalTransaction(MessageExt msg) {
        //         return null;
        //     }
        // });
        // try {
        //     transactionMQProducer.sendMessageInTransaction(null,"");
        // } catch (MQClientException e) {
        //     e.printStackTrace();
        // }

        defaultMQProducer = new DefaultMQProducer(RocketMQProtocolEnum.SECKILL_TEST_TOPIC.getProducerGroup());
        defaultMQProducer.setNamesrvAddr(customRocketMQConfig.getNameSrvAddr());
        // 发送失败重试次数
        defaultMQProducer.setRetryTimesWhenSendFailed(3);
        try {
            defaultMQProducer.start();
        } catch (MQClientException e) {
            LOG.error("[秒杀订单生产者]--SecKillChargeOrderProducer加载异常!e=", e);
            throw new DiyRuntimeException("[秒杀订单生产者]--SecKillChargeOrderProducer加载异常!");
        }
        LOG.info("[秒杀订单生产者]--SecKillChargeOrderProducer加载完成!");
    }

    public DefaultMQProducer getProducer() {
        return defaultMQProducer;
    }
}
